package isv

import (
	"dhfshop/controllers/base"
	"dhfshop/models/isv"
	"time"
	"github.com/astaxie/beego/validation"
)

type WxAppController struct {
	base.BaseController
}

// 查询微信小程序
func (this *WxAppController) GetWxapp() {
	query,_, fields, order_by, offset, limit, err := this.GetQueryPara()
	if err != nil {
		this.ServeError(err.Error())
		return
	}
	l, cnt, err := isv.GetAllWxapps(query, fields, order_by, offset, limit)
	if err != nil {
		this.ServeError(err.Error())
		return
	}
	r := struct {
		TotalCount int64        `json:"total_count"`
		Wxapps     []*isv.Wxapp `json:"wxapps"`
	}{TotalCount: cnt, Wxapps: l}
	this.Data["json"] = r
	this.ServeJSON()
}

// 添加一个微信小程序的版本
func (this *WxAppController) AddWxapp() {
	var v isv.Wxapp
	this.ParseForm(&v)
	valid := validation.Validation{}
	valid.Required(v.AppType, "app_type")
	valid.Required(v.TemplateId, "template_id")
	valid.Required(v.Statu, "statu")
	valid.Required(v.Version, "version")
	valid.Required(v.Description, "description")
	passed, _ := valid.Valid(&v)
	if !passed {
		this.ServeError(valid.Errors[0].Key + " " + valid.Errors[0].Message)
		return
	}
	id, err := isv.AddWxapp(&v)
	if err != nil {
		this.ServeError(err.Error())
		return
	}
	v.AppId = id
	this.Data["json"] = v
	this.ServeJSON()
}

// 更新一个微信小程序的版本
func (this *WxAppController) UpdateWxapp() {
	var v isv.Wxapp
	this.ParseForm(&v)
	valid := validation.Validation{}
	valid.Required(v.AppId, "appid")
	passed, _ := valid.Valid(&v)
	if !passed {
		this.ServeError(valid.Errors[0].Key + " " + valid.Errors[0].Message)
		return
	}
	updateFields, err := this.GetUpdateFields(v,"", "form", []string{""})
	if err != nil {
	  this.ServeError(err.Error())
		return
	}
	if len(updateFields) > 0 {
	    err := isv.UpdateWxapp(&v, updateFields...)
		if err != nil {
			this.ServeError(err.Error())
			return
		}
	}
	rsp := struct {
		AppId     int64       `json:"appid"`
	    Modified  time.Time   `json:"modified"`
	}{AppId:v.AppId, Modified:time.Now().UTC()}
	this.Data["json"] = rsp
	this.ServeJSON()
}

// 删除一个版本
func (this *WxAppController) DeleteWxapp() {
	var v isv.Wxapp
	this.ParseForm(&v)
	valid := validation.Validation{}
	valid.Required(v.AppId, "appid")
	passed, _ := valid.Valid(&v)
	if !passed {
		this.ServeError(valid.Errors[0].Key + " " + valid.Errors[0].Message)
		return
	}
	err := isv.DeleteWxapp(v.AppId)
	if err != nil {
		this.ServeError(err.Error())
		return
	}
	r := struct {
		Appid    int64       `json:"appid"`
		Modified time.Time `json:"modified"`
	}{Appid: v.AppId, Modified: time.Now().UTC()}
	this.Data["json"] = r
	this.ServeJSON()
}
